package com.earnings.okhttputils.utils.ui.fragment.transaction;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.earnings.R;
import com.earnings.databinding.ItemAmountBinding;
import com.earnings.databinding.ItemAmountFlowBinding;
import com.earnings.databinding.ItemSubsidyBinding;
import com.earnings.okhttputils.utils.OkHttp.OkHttpUtils;
import com.earnings.okhttputils.utils.UrlConstant.Constant;
import com.earnings.okhttputils.utils.UrlConstant.HttpUrl;
import com.earnings.okhttputils.utils.User;
import com.earnings.okhttputils.utils.adapter.DataBindingBaseadapter;
import com.earnings.okhttputils.utils.adapter.DataBindingViewHolder;
import com.earnings.okhttputils.utils.bean.RechargeData;
import com.earnings.okhttputils.utils.bean.RechargeFlowData;
import com.earnings.okhttputils.utils.bean.RechargeFlowItemData;
import com.earnings.okhttputils.utils.bean.RechargeOrderData;
import com.earnings.okhttputils.utils.bean.RechargeSubisidyData;
import com.earnings.okhttputils.utils.https.HttpArrayCallback;
import com.earnings.okhttputils.utils.https.HttpMap;
import com.earnings.okhttputils.utils.https.HttpObjectCallback;
import com.earnings.okhttputils.utils.ui.BaseFragment;
import com.earnings.okhttputils.utils.ui.activity.common.StatusPriceActivity;
import com.earnings.okhttputils.utils.ui.activity.common.WebActivity;
import com.earnings.okhttputils.utils.utils.CommonUtil;
import com.earnings.okhttputils.utils.utils.PayUtil;
import com.earnings.okhttputils.utils.view.FullStaggeredGridLayoutManager;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 话费油卡充值
 * Created by HOHO on 2017/4/11.
 */

public class RechargeFragment extends BaseFragment {


    public static final int RECHARGE_BILL = 1;//话费充值
    public static final int RECHARGE_FLOW = 4;//流量充值
    public static final int RECHARGE_SINOPEC = 2;//中国石化
    public static final int RECHARGE_PETROLEUM = 3;//中国石油
    public int nowType = 1;
    private Map<Integer, View> amountMap, subsidyMap;
    private View phoneview, oilview;
    private RecyclerView amount, subsidy;
    private DataBindingBaseadapter baseAdapter;
    private TextView phoneInfo, subisidyInfo, price;
    private EditText phone, oilcard;
    private String subisidy, planid, pid, flow, cardnum;
    private float money, frate, brate, num;
    private String allmoney;

    private User user;
    public void Type(int choose) {
        nowType = choose;
    }


    @Override
    protected int onCreateLayout() {
        return R.layout.fragment_recharge_content;
    }

    public void init() {
        phone = (EditText) mView.findViewById(R.id.phone);
        phoneInfo = (TextView) mView.findViewById(R.id.phoneInfo);
        price = (TextView) mView.findViewById(R.id.price);
        subisidyInfo = (TextView) mView.findViewById(R.id.subisidyInfo);
        phoneview = mView.findViewById(R.id.phoneview);
        oilview = mView.findViewById(R.id.oilview);
        oilcard = (EditText) mView.findViewById(R.id.oilcard);
        amount = (RecyclerView) mView.findViewById(R.id.amount);
        subsidy = (RecyclerView) mView.findViewById(R.id.subsiby);
        mView.findViewById(R.id.sumbit).setOnClickListener(this);
        mView.findViewById(R.id.phone_people).setOnClickListener(this);
        mView.findViewById(R.id.agreement).setOnClickListener(this);
        money=0;
        num=0;
        user=CommonUtil.getUser();

        showProgress();
        if (nowType == RechargeFragment.RECHARGE_FLOW)
            loadRechargeFlowListData();//读取流量的金额列表
        else
            loadRechargeListData();//读取非流量的金额列表
        //   loadRechargeSubisidyListData();//读取方案列表
        initPhoneChange();//监听电话状态

        switch (nowType) {
            case RECHARGE_BILL:
                phoneview.setVisibility(View.VISIBLE);
                break;
            case RECHARGE_FLOW:
                phoneview.setVisibility(View.VISIBLE);
                break;
            case RECHARGE_SINOPEC:
                oilview.setVisibility(View.VISIBLE);
                oilcard.setText(user.getOilcard1());
                break;
            case RECHARGE_PETROLEUM:{
                oilcard.setHint( "请输入16位中国石油加油卡号");
                oilview.setVisibility(View.VISIBLE);
                oilcard.setText(user.getOilcard2());

            }
                break;
        }

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        int i = v.getId();
        if (i == R.id.sumbit) {
            createRechargeOrder();


        } else if (i == R.id.phone_people) {//   showToast( "123" );
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                //如果没有授权，则请求授权
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_CONTACTS}, 1);
            } else {

                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                intent.setData(ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, REQUEST_CONTACT);
            }

        } else if (i == R.id.agreement) {//点击用户协议
            bundleData.putString("title", "招财汇宝充值平台服务协议");
            bundleData.putString("url", "http://www.baishisc.com/index.php/Api/Article/detail/article_id/34");
            skip(WebActivity.class);

        }
    }


    /*
    监听电话状态
     */
    public void initPhoneChange() {
        if (nowType == RechargeFragment.RECHARGE_FLOW || nowType == RechargeFragment.RECHARGE_BILL) {
            loadPhoneAttribution(CommonUtil.getUser().getPhone());
            phone.setText(CommonUtil.getUser().getPhone());
            phone.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (phone.getText().length() != 11) {
                        phoneInfo.setText("请输入正确的手机号码");
                    } else {
                        loadPhoneAttribution(phone.getText().toString());
                    }
                }
            });
        }
    }

    public void initAmount() {
        subisidyInfo.setText(subisidy);
        float priceText = money * num + (money * num * frate);
        allmoney = new DecimalFormat(".00").format(priceText);
        price.setText(allmoney + "元");
    }

    /*
   获取金额列表
     */

    public void initAmountData(final List<RechargeData> datas) {
        amountMap = new HashMap<Integer, View>();
        amount.setLayoutManager(new FullStaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        baseAdapter = new DataBindingBaseadapter<RechargeData, ItemAmountBinding>(getActivity(), datas, R.layout.item_amount) {

            @Override
            public void convert(DataBindingViewHolder holder, ItemAmountBinding binding, RechargeData homeButton) {


                binding.setRecharge(homeButton);
                final int position = holder.getLayoutPosition();
                if (position == 0&&money==0) {
                    holder.getView(R.id.view).setBackgroundResource(R.drawable.bg_style_round);
                    money = datas.get(position).getMoney();
                    ((TextView) holder.getView(R.id.priceRecharge)).setTextColor(mView.getResources().getColor(R.color.white));

                }
                if (amountMap.get(position) == null)
                    amountMap.put(position, holder.getView(R.id.view));
            }

            @Override
            public void onItemClick(DataBindingViewHolder holder, RechargeData homeButton) {


                for (int i = 0; i < datas.size(); i++) {
                    View view = amountMap.get(i);
                    view.setBackgroundResource(R.drawable.bg_white_round_style_line);
                    ((TextView) amountMap.get(i).findViewById(R.id.priceRecharge)).setTextColor(mView.getResources().getColor(R.color.style));

                }
                int position = holder.getLayoutPosition();
                money = datas.get(position).getMoney();

                initAmount();
                View view = holder.getView(R.id.view);
                view.setBackgroundResource(R.drawable.bg_style_round);
                ((TextView) view.findViewById(R.id.priceRecharge)).setTextColor(view.getResources().getColor(R.color.white));
            }
        };

        amount.setAdapter(baseAdapter);

    }


    /*
   获取流量金额列表
     */
    //
    public void initAmountFlowData(final List<RechargeFlowItemData> datas) {
        amountMap = new HashMap<Integer, View>();
        amount.setLayoutManager(new FullStaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        baseAdapter = new DataBindingBaseadapter<RechargeFlowItemData, ItemAmountFlowBinding>(getActivity(), datas, R.layout.item_amount_flow) {

            @Override
            public void convert(DataBindingViewHolder holder, ItemAmountFlowBinding binding, RechargeFlowItemData homeButton) {
                binding.setRecharge(homeButton);
                final int position = holder.getLayoutPosition();
                if (position == 0&&money==0) {
                    holder.getView(R.id.view).setBackgroundResource(R.drawable.bg_style_round);
                    ((TextView) holder.getView(R.id.priceRecharge)).setTextColor(mView.getResources().getColor(R.color.white));
                    ((TextView) holder.getView(R.id.info)).setTextColor(mView.getResources().getColor(R.color.white));

                    money = Float.parseFloat(datas.get(position).getInprice().replace("元", ""));
                    pid = datas.get(position).getId();
                    flow = datas.get(position).getV();
                }
                if (amountMap.get(position) == null)
                    amountMap.put(position, holder.getView(R.id.view));
            }

            @Override
            public void onItemClick(DataBindingViewHolder holder, RechargeFlowItemData homeButton) {
                for (int i = 0; i < datas.size(); i++) {
                    View view = amountMap.get(i);
                    view.setBackgroundResource(R.drawable.bg_white_round_style_line);
                    ((TextView) amountMap.get(i).findViewById(R.id.priceRecharge)).setTextColor(mView.getResources().getColor(R.color.style));
                    ((TextView) amountMap.get(i).findViewById(R.id.info)).setTextColor(mView.getResources().getColor(R.color.textmiddle));

                }

                View view = holder.getView(R.id.view);
                view.setBackgroundResource(R.drawable.bg_style_round);
                ((TextView) view.findViewById(R.id.priceRecharge)).setTextColor(view.getResources().getColor(R.color.white));
                ((TextView) view.findViewById(R.id.info)).setTextColor(view.getResources().getColor(R.color.white));

                int position = holder.getLayoutPosition();
                money = Float.parseFloat(datas.get(position).getInprice().replace("元", ""));
                pid = datas.get(position).getId();
                flow = datas.get(position).getV();
                initAmount();
            }
        };

        amount.setAdapter(baseAdapter);

    }

    /*
     方案列表
      */ //TODO rc少item
    public void initSubsidyData(final List<RechargeSubisidyData> datas) {
        subsidyMap = new HashMap<>();
        //subsidy.setLayoutManager(new FullStaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        subsidy.setLayoutManager(new LinearLayoutManager(getActivity()));

        baseAdapter = new DataBindingBaseadapter<RechargeSubisidyData, ItemSubsidyBinding>(getActivity(), datas, R.layout.item_subsidy) {

            @Override
            public void convert(DataBindingViewHolder holder, ItemSubsidyBinding binding, RechargeSubisidyData homeButton) {

                binding.setRecharge(homeButton);
                final int position = holder.getLayoutPosition();
                if (position == 0&&num==0) {
                    ((ImageView) holder.getView(R.id.icon)).setImageResource(R.mipmap.check_true);
                    frate = datas.get(position).getFrate();
                    num = datas.get(position).getNum();
                    brate = datas.get(position).getBrate();
                    subisidy = datas.get(position).getTitle();
                    initAmount();
                }
                if (subsidyMap.get(position) == null)
                    subsidyMap.put(position, holder.getView(R.id.icon));

            }

            @Override
            public void onItemClick(DataBindingViewHolder holder, RechargeSubisidyData msgData) {
                final int position = holder.getLayoutPosition();
                for (int i = 0; i < datas.size(); i++) {
                    ((ImageView) subsidyMap.get(i)).setImageResource(R.mipmap.check_false);
                    if (i == position) {
                        ((ImageView) subsidyMap.get(i)).setImageResource(R.mipmap.check_true);
                        frate = datas.get(i).getFrate();
                        num = datas.get(i).getNum();
                        brate = datas.get(i).getBrate();
                        subisidy = datas.get(i).getTitle();
                        planid=datas.get(i).getPlanid();
                        initAmount();
                    }


                }



            }
        };

        subsidy.setAdapter(baseAdapter);
    }


/*
获取充值面额
 */

    public void loadRechargeListData() {

        Map map = new HttpMap(getActivity());
        map.put("typeid", nowType + "");
        OkHttpUtils.post().url(HttpUrl.RECHARGE_AMOUNT_LIST_URL).params(map).build().execute(new HttpArrayCallback<RechargeData>(getContext()) {
            @Override
            public void onSuccess(List<RechargeData> response, String msg) {
                initAmountData(response);
                loadRechargeSubisidyListData();
            }

            @Override
            public void onFail(int code, String msg) {

                showToast(msg);
            }

        });
    }

    /*
获取流量充值面额
 */

    public void loadRechargeFlowListData() {

        Map map = new HttpMap(getActivity());
        map.put("mobile", CommonUtil.getUser().getPhone());
        OkHttpUtils.post().url(HttpUrl.RECHARGE_FLOW_AMOUNT_LIST_URL).params(map).build().execute(new HttpObjectCallback<RechargeFlowData>(getContext()) {
            @Override
            public void onSuccess(RechargeFlowData object, String msg) {
                initAmountFlowData(object.getFlows());
                loadRechargeSubisidyListData();

            }

            @Override
            public void onFail(int code, String msg) {
                showToast(msg);
            }


        });
    }

       /*
创建订单
 */

    public void createRechargeOrder() {

        Map map = new HttpMap(getContext());
        //参数名 参数类型 必传 缺省值 描述
        map.put("cishu", num + "");//	充值次数" +
        map.put("money", money + "");
        map.put("userid", CommonUtil.getUser().getUser_id());
        map.put("pid", pid);
        map.put("flow", flow);
        map.put("planid", planid);
        //    map.put( "belong_trade_sn", CommonUtil.getUser().getMobile() );
        if (nowType == RECHARGE_BILL) map.put("typeid", "2");//充值类型;1加油卡、2电话、3流量
        else if (nowType == RECHARGE_FLOW) map.put("typeid", "3");
        else {
            map.put("typeid", "1");
            if (nowType == RECHARGE_SINOPEC) map.put("type", "1");
            else map.put("type", "2");
        }


        map.put("cardnum", (int) money + "");
        if (nowType == RECHARGE_BILL || nowType == RECHARGE_FLOW)
            map.put("number", phone.getText().toString());
        else if(nowType == RECHARGE_SINOPEC){
            user.setOilcard1(oilcard.getText().toString());
            CommonUtil.commitUser(user);
            map.put("number", oilcard.getText().toString());
        } else if(nowType == RECHARGE_PETROLEUM){
            user.setOilcard2(oilcard.getText().toString());
            CommonUtil.commitUser(user);
            map.put("number", oilcard.getText().toString());
        }
        map.put("username", CommonUtil.getUser().getPhone());
        map.put("tel", CommonUtil.getUser().getPhone());
        OkHttpUtils.post().url(HttpUrl.RECHARGE_ORDER_CREATE_URL).params(map).build().execute(new HttpObjectCallback<RechargeOrderData>(getContext()) {
            @Override
            public void onSuccess(final RechargeOrderData object, String msg) {
                new PayUtil(getActivity(), allmoney) {

                    @Override
                    public void onSuccess(String info, String price) {
                        bundleData.putString("title", object.getOrder_intro());
                        bundleData.putString("info", "");
                        bundleData.putString("status", "充值成功");
                        bundleData.putString("price", price);
                        skip(StatusPriceActivity.class);
                        getActivity().finish();
                    }
                }.showRechargeOil(object.getTrade_sn(), object.getOrder_intro());


            }

            @Override
            public void onFail(int code, String msg) {
                showToast(msg);
            }


        });
    }
    /*
   获取充值方案
 */

    public void loadRechargeSubisidyListData() {

        Map map = new HttpMap(getActivity());

        OkHttpUtils.post().url(HttpUrl.RECHARGE_SUBSIDY_LIST_URL).params(map).build().execute(new HttpArrayCallback<RechargeSubisidyData>(getContext()) {
            @Override
            public void onSuccess(List<RechargeSubisidyData> object, String msg) {
                initSubsidyData(object);
                dismissProgress();
            }

            @Override
            public void onFail(int code, String msg) {
                showToast(msg);dismissProgress();
            }


        });
    }

   /*
   查询手机归属地
 */

    public void loadPhoneAttribution(String phone) {

        Map map = new HttpMap(getActivity());

        map.put("mobile", phone);
        OkHttpUtils.post().url(HttpUrl.RECHARGE_PHONE_INFO_URL).params(map).build().execute(new HttpObjectCallback<String>(getContext()) {
            @Override
            public void onSuccess(String object, String msg) {
                phoneInfo.setText(object.replace("\"", ""));
                dismissProgress();
            }

            @Override
            public void onFail(int code, String msg) {
                if (code == Constant.STATUS_SERVER_RETURN)
                    phoneInfo.setText(msg);
                else
                    showToast(msg);
                dismissProgress();
            }


        });
    }

    private static final int REQUEST_CONTACT = 0;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CONTACT && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            // 得到ContentResolver对象
            ContentResolver cr = getActivity().getContentResolver();
            // 取得电话本中开始一项的光标
            Cursor cursor = cr.query(uri, null, null, null, null);
            // 向下移动光标
            while (cursor.moveToNext()) {
                // 取得联系人名字
                int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
                String contact = cursor.getString(nameFieldColumnIndex);
                // 取得电话号码
                String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
                //不只一个电话号码
                while (phone.moveToNext()) {
                    String phoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replace(" ", "");
                    this.phone.setText(phoneNumber);

                    break; //只取一个电话号码
                }
            }
        }
    }
}
